package com.sangmo.fts.restructure.aspect;

import com.sangmo.boot.framework.common.utils.ExpressionUtils;
import com.sangmo.fts.restructure.meta.TrainingProcess;
import com.sangmo.fts.training.model.TrainingHistory;
import com.sangmo.fts.training.service.TrainingHistoryEntityService;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Aspect
public class TrainingProcessAspect {

    @Autowired
    private TrainingHistoryEntityService trainingHistoryEntityService;

    @AfterReturning(value = "@annotation(trainingProcess)")
    public void doAfterReturning(JoinPoint point, TrainingProcess trainingProcess) throws Throwable {

            MethodSignature signature = (MethodSignature) point.getSignature();
            Map<String, Object> parameters = new HashMap();

            String[] names = signature.getParameterNames();
            for (int i = 0; i < names.length; i++) {
                parameters.put(names[i], point.getArgs()[i]);
            }

            Object id = ExpressionUtils.readValue(trainingProcess.indicator(), parameters);
            createProcessNode(trainingProcess.node(), id);
    }


    private void createProcessNode(String processNode, Object id) {
        Object[] ids = null;
        if (id instanceof Collection) {
            ids = ((Collection)id).toArray();
        } else {
            ids = new Object[] {id};
        }

        for (Object trainingId : ids) {
            TrainingHistory th = new TrainingHistory();
            th.setTrainingId((Long)trainingId);
            th.setProcessNode(processNode);
            trainingHistoryEntityService.create(th);
        }
    }
}
